//
//  MCFlowButtonView.swift
//  swiftOfAfn
//
//  Created by Mikey on 16/10/17.
//  Copyright © 2016年 mikey. All rights reserved.
//

import UIKit

class MCFlowButtonView: UIView {

    var buttonList = [UIButton]()
    
    var margin:CGFloat = 10
    
    func initWithButtonList(buttonList:[UIButton]) {
        self.buttonList = buttonList
        for btn in self.buttonList {
            addSubview(btn)
        }
    }
    
    public func refreshFrame() -> CGRect {
        
        // 存放每行的第一个button
        var rowFirstButtons = [UIButton]()
        
        // 对第一个button进行设置
        let button0 = buttonList[0]
        var btnRect = button0.frame
        btnRect.origin.x = 10
        btnRect.origin.y = 10
        button0.frame = btnRect
        rowFirstButtons.append(buttonList[0])
        
        // 对其他button设置
        var row = 0
        for i in 1 ..< buttonList.count {
            let button = buttonList[i]
            
            var sumWidth:CGFloat = 0
            let start = buttonList.index(of: rowFirstButtons[row])
            for j in start!...i {
                let button = buttonList[j]
                sumWidth += button.frame.size.width + margin
            }
            sumWidth += 10
            
            let lastButton = buttonList[i - 1]
            if sumWidth >= self.frame.size.width {
                btnRect = button.frame
                btnRect.origin.x = margin
                btnRect.origin.y = lastButton.frame.origin.y + margin + button.frame.size.height
                button.frame = btnRect
                rowFirstButtons.append(button)
                row += 1
            } else {
                btnRect = button.frame
                btnRect.origin.x = sumWidth - margin - button.frame.size.width
                btnRect.origin.y = lastButton.frame.origin.y
                button.frame = btnRect
            }
        }
        
        let endButton = buttonList.last
        var rect = self.frame
        rect.size.height = endButton!.frame.origin.y + endButton!.frame.size.height + 10
        self.frame = rect
        return self.frame
    }

}
